package com.ruoyi.fjtseac.service.impl;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.fjtseac.domain.po.Video;
import com.ruoyi.fjtseac.mapper.AudioMapper;
import com.ruoyi.fjtseac.mapper.CronJobMapper;
import com.ruoyi.fjtseac.mapper.EssayMapper;
import com.ruoyi.fjtseac.mapper.VideoMapper;
import com.ruoyi.fjtseac.util.aop.TableEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 定时任务服务类
 *
 * @author zzl
 * @date 2022/8/4 20:51
 */
@Component
@EnableScheduling
public class CronJobServiceImpl {

    @Autowired
    RedisCache redis;
    @Autowired
    CronJobMapper cronJobMapper;

    private final String[] tables = {TableEnum.ESSAY.getTableName(), TableEnum.VIDEO.getTableName()};

    // 凌晨三点将缓存的浏览量写入数据库。
    @Scheduled(cron = "0 0 3 * * ?")
    public void censusPV() {
        for (String table : tables) {
            String key = table + ":" + "*";
            Collection<String> keys = redis.keys(key);
            if (keys != null && keys.size() != 0) {
                keys.forEach(k -> {
                    Integer pv = redis.getCacheObject(k);
                    Integer id = Integer.valueOf(k.replaceAll(table + ":", ""));
                    switch (table) {
                        case "essay":
                            cronJobMapper.censusEssayPV(id, pv);
                            break;
                        case "video":
                            cronJobMapper.censusVideoPV(id, pv);
                            break;
                        default:
                            throw new ServiceException().setMessage("table值不合法");
                    }
                });
            }
        }
    }


}
